package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.CategoryModel;

import admin.data.CategoryData;
import admin.forms.CategoryForm;

public class AddCategoryServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		CategoryData categoryData = new CategoryData();
		CategoryModel category = new CategoryModel();
		category.setCategoryId(IdUniqueHelper.getId());
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("category", category);
		try {
			request.getRequestDispatcher("/admin/pages/form_category.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		CategoryData categoryData = new CategoryData();
		CategoryModel category = new CategoryModel();
		
		CategoryForm categoryForm = new CategoryForm();
		TreeMap form = (TreeMap) categoryForm.checkValid(request, category);
		category = (CategoryModel) form.get("category");
		check = (TreeMap) form.get("checkValid");
		
		if (check.size() == 0) {
			categoryData.insert(category);
			category = new CategoryModel();
			category.setCategoryId(IdUniqueHelper.getId());
			request.setAttribute("success", "Bạn đã thêm danh mục thành công.");
		}
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("category", category);
		try {
			request.getRequestDispatcher("/admin/pages/form_category.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
